/**
 * Author: weizq@autoai.com
 * Create Time: 2019/07/01 16:50
 * Description:
 */
import Vue from 'vue'
/**
 * 四维地图组件
 * 示例： <m-map :on-load="mapLoad" center="116.40049,39.9208" style="width: 100%;height: 200px;"/>
 *       mapLoad: function(maplet){}
 */

const loadMapApi = function (url, callback, errorCallback) {
    let script = document.createElement('script')
    script.type = 'text/javascript'
    let params = {
        window: window
    }
    function getCallbackParams () {
        return params
    }
    if (script.readyState) { // IE
        script.onreadystatechange = function () {
            if (script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null
                callback()// callback(getCallbackParams())
            }
        }
    } else { // Others
        script.onload = function () {
            callback()// callback(getCallbackParams())
        }
    }
    script.onerror = function () { // 顺序必须在append之前
        errorCallback(getCallbackParams())
    }
    script.src = url

    document.body.appendChild(script)
}

let isFetching = false, mapletPromise = null
const getMaplet = function () {
    if (!isFetching) {
        isFetching = true
        mapletPromise = new Promise((resolve, reject) => {
            if (window['Maplet']) {
                isFetching = false
                resolve(window['Maplet'])
            } else {
                loadMapApi(
                    'https://nmap.autoai.com/sdk/js/map?ak=T7O1153xJX1779535313y3Y5RkPJAdT7',
                    () => {
                        Vue.nextTick(() => {
                            isFetching = false
                            resolve(window['Maplet'])
                        })
                    }),
                    (err) => {
                        isFetching = false
                        reject(err)
                    }
            }
        })
    }
    return mapletPromise
}
export default {
    data () {
        return {
            maplet: null,
            operateType: '',
            circle: null,
            mouseTool: null
        }
    },
    props: {},
    methods: {
        // 激活地图标注功能
        mapMarker () {},
        // 激活地图画圆功能
        mapCircle (r) {
            this.operateType = 'circle'
            this.maplet.setCursor("crosshair");
            this.clearBefore()
            this.circle = new nglp.Circle({
                center: "116.403322, 39.920255",  // 圆心位置
                radius: r,  //半径
                'fill-color': '#ee2200',
                'fill-opacity':  0.35,
                'fill-antialias':true,
                'fill-outline-color': "#F33",
            });
        },
        // 激活地图画多边形功能
        mapPolygon () {
            this.clearBefore()
            this.mouseTool.polygon({
                'fill-color': '#ee2200',
                'fill-opacity':  0.35,
                'fill-antialias':true,
                'fill-outline-color': "#F33",
            });
        },
        // 点击触发
        eventClick (events) {
            if (this.operateType === 'circle') {
                // this.maplet.removeLayer(this.circle);
                this.circle.setCenter(events.lngLat.toString())
                this.circle.addTo(this.maplet)
                this.$emit('callback', events.lngLat.toString())
            }
            this.maplet.setCursor("default")
            this.operateType = ''
        },
        // 清除之前的画布
        clearBefore () {
            if (this.circle) {
                this.maplet.removeLayer(this.circle)
                this.circle = null
            }
            this.mouseTool.close(false)
        }
    },
    async mounted () {
        // 初始化地图
        await getMaplet()
        this.maplet = new nglp.Map({
            container: 'map',
            style: 'https://nmap.autoai.com/res/styles/normal/style.json',
            zoom: 11, //初始化地图层级
            center: [116.397428, 39.90923], //初始化地图中心点
            doubleClickZoom: false
        })
        this.maplet.on('click', events => this.eventClick(events))
        this.mouseTool =  new nglp.MouseTool(this.maplet);
        this.mouseTool.on('draw', overlay => {
            this.$emit('callback', overlay.path)
            setTimeout(()=> {
                this.mouseTool.close(true)
            }, 100)
        });
    },
    destroyed () {},
    activated () {},
    deactivated () {},
    render (createElement) {
        return createElement('div', { attrs: { id: 'map' }, style: { width: '100%', height: '600px' } })
    }

}
